<?php
/**
 * Created by 餐厅类.
 * User: 尚金殿
 * Date: 2018/8/25
 * Time: 12:44
 */

namespace app\admin\controller;


use think\Db;

class RestaurantController extends CommonController
{
    protected $mysql = 'island_restaurant';
    protected $pk = 'id';
    protected $name = 'name';
    protected $status = 'status';


    //餐厅添加
    public function add(){
        if($this->request->isPost()){
            //获取提交的数据
            $data = $this->request->param();

            //判定数据
            if(!$data['island_id'] || !is_numeric($data['island_id'])){
                return show(0,'所属岛屿不能为空');
            }
            if(!$data['name']){
                return show(0,'餐厅名称不能为空');
            }

            //判定是么有ID
            if(!empty($data['id'])){
                $this->save($data);
            }
            //判定有没有轮播
            if(isset($data['img'])){
                $slider['img'] = implode(',',$data['img']);
                unset($data['img']);
            }

            //入库
            $id = $this->getAdd($data);

            if($id){
                //入库轮播表
                $slider['restaurant_id'] = $id;
                $slider['status'] = 1;
                $res = Db::name('slider')->insertGetId($slider);

                if(!$res){
                    return show(0,'新增失败');
                }
                    return show(1,'新增成功');

            }
        }else{
            //获取全部的岛屿
            $island = Db::name('island')->where('status','>',-1)->select();

            //变量输出
            $this->assign('island',$island);

            //加载模版
            return $this->fetch();
        }
    }

    //餐厅编辑
     public function edit(){
        $id = $this->request->param('id');

        //获取所属岛屿
         $island = Db::name('island')->where('status','>',-1)->select();

         //获取餐厅数据
        $res = Db::name($this->mysql)->where($this->pk,$id)->find();

        //获取轮播数据
        $img = Db::name('slider')->where('restaurant_id',$id)->find();
        $res['img'] = $img['img'];

        //分配数据
        $this->assign(['island'=>$island,'res'=>$res]);

        //加载模版
        return $this->fetch();
     }

    //保存编辑
    public function save($data){
         if(!$data || !is_array($data)){
             return show(0,'传递的数据不合法');
         }

        $id = $data[$this->pk];
        unset($data[$this->pk]);
        $data['update_time'] = time();

        //判定有么有轮播
        if(isset($data['img'])){
            $slider['img'] = implode(',',$data['img']);
            unset($data['img']);
        }


        //修改线路主库数据
        $res = Db::name($this->mysql)->where($this->pk,$id)->update($data);


        if($res){
            Db::name('slider')->where('restaurant_id',$id)->update($slider);

            return show(1,'更新成功');
        }
    }
}